package com.ssy.lingxi.marketing.serviceimpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.ssy.lingxi.common.constant.manage.ShopTypeEnum;
import com.ssy.lingxi.common.constant.marketing.ActivityTypeEnum;
import com.ssy.lingxi.common.constant.marketing.BelongTypeEnum;
import com.ssy.lingxi.common.constant.product.PriceTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.bo.MemberAndRoleIdBO;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.marketing.constant.MarketingFieldsEnum;
import com.ssy.lingxi.marketing.entity.activity.ActivityGoodsDO;
import com.ssy.lingxi.marketing.entity.activity.MerchantActivityDO;
import com.ssy.lingxi.marketing.entity.activity.PlatformActivityDO;
import com.ssy.lingxi.marketing.model.bo.*;
import com.ssy.lingxi.marketing.model.constant.*;
import com.ssy.lingxi.marketing.model.vo.activity.request.ActivityCardAdornReq;
import com.ssy.lingxi.marketing.model.vo.activity.request.GoodsAreaAdornReq;
import com.ssy.lingxi.marketing.model.vo.activity.response.ActivityCardAdornResp;
import com.ssy.lingxi.marketing.model.vo.activity.response.GoodsAreaAdornResp;
import com.ssy.lingxi.marketing.model.vo.coupon.request.BelongTypeCouponRequest;
import com.ssy.lingxi.marketing.repository.ActivityGoodsRepository;
import com.ssy.lingxi.marketing.repository.ActivityGoodsSubsidiaryRepository;
import com.ssy.lingxi.marketing.repository.MerchantActivityRepository;
import com.ssy.lingxi.marketing.repository.PlatformActivityRepository;
import com.ssy.lingxi.marketing.service.ICouponReceiveService;
import com.ssy.lingxi.marketing.service.IMobileActivityService;
import com.ssy.lingxi.marketing.serviceimpl.base.activity.BaseActivityService;
import com.ssy.lingxi.marketing.serviceimpl.component.activity.ActivityGoodsHandleComponent;
import com.ssy.lingxi.marketing.serviceimpl.component.activity.ActivityPriceCalculateComponent;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberLevelRightCreditControllerFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignManageUpperMemberAndRoleVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignRelationVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignManageMemberCreditParameterVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignRightVO;
import com.ssy.lingxi.platform.manage.api.feign.inner.ShopControllerFeign;
import com.ssy.lingxi.platform.manage.api.model.dto.common.CommonIdListDTO;
import com.ssy.lingxi.platform.manage.api.model.vo.shop.ShopVO;
import com.ssy.lingxi.product.api.feign.ICommodityFeign;
import com.ssy.lingxi.product.api.model.request.feign.CommodityNameRequest;
import com.ssy.lingxi.product.api.model.request.feign.CommodityPublishRequest;
import com.ssy.lingxi.search.api.feign.ISearchFeign;
import com.ssy.lingxi.product.api.model.request.feign.CommodityNameRequest;
import com.ssy.lingxi.product.api.model.request.feign.CommodityPublishRequest;
import com.ssy.lingxi.search.api.feign.ITemplateChannelFeign;
import com.ssy.lingxi.search.api.feign.ITemplateFeign;
import com.ssy.lingxi.search.api.model.request.CommoditySkuRequest;
import com.ssy.lingxi.search.api.model.request.TemplateCommoditySearchRequest;
import com.ssy.lingxi.search.api.model.request.channel.TemplateChannelCommoditySearchRequest;
import com.ssy.lingxi.search.api.model.response.CommoditySearchResponse;
import com.ssy.lingxi.search.api.model.response.CommoditySkuResponse;
import com.ssy.lingxi.search.api.model.response.channel.ChannelCommoditySearchResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;

/**
 * mobile - 活动服务实现类
 *
 * @author fhj
 * @version 2.0.0
 * @date 2021/09/07
 */
@Slf4j
@Service
public class MobileActivityServiceImpl implements IMobileActivityService {

    @Resource
    private ActivityGoodsRepository goodsRepository;
    @Resource
    private ActivityGoodsSubsidiaryRepository goodsSubsidiaryRepository;
    @Resource
    private PlatformActivityRepository platformActivityRepository;
    @Resource
    private MerchantActivityRepository merchantActivityRepository;
    @Resource
    private ITemplateFeign templateFeign;
    @Resource
    private ICouponReceiveService couponCalculateService;
    @Resource
    private ICommodityFeign commodityFeign;
    @Resource
    private ActivityGoodsHandleComponent activityGoodsHandleComponent;
    @Resource
    private ActivityPriceCalculateComponent activityPriceCalculateComponent;
    @Resource
    private BaseActivityService baseActivityService;
    @Resource
    private ITemplateChannelFeign templateChannelFeign;
    @Resource
    private ISearchFeign searchFeign;
    @Resource
    private ShopControllerFeign shopControllerFeign;
    @Resource
    private MemberLevelRightCreditControllerFeign memberLevelRightCreditControllerFeign;

    /**
     * 平台活动页（装修）
     **/
    @Override
    public Wrapper<Map<String, Object>> platformActivityPageAdorn(JSONObject req, Long shopId, UserLoginCacheDTO user) {
        //处理数据BigDecimal 专用
        DecimalFormat decimalFormat = new DecimalFormat("##########.##########");
        //定义返回体
        Map<String, Object> result = new HashMap<>();
        //获取区域编码
        String pCode = "0";
        String cCode = "0";
        JSONArray area = req.getJSONArray("area");
        if (area != null) {
            List<String> areaList = area.toList(String.class);
            if (area.size() > 0) {
                pCode = areaList.get(0);//省code
                cCode = areaList.get(1);//市code
            }
        }
        //移除数据,防止循环操作时数据多余
        req.remove("area");
        //获取所有key，根据每个key对应的id数组查询对应的数据并组装回去
        Set<String> keySet = req.keySet();
        String finalPCode = pCode;
        String finalCCode = cCode;
        keySet.forEach(key -> {

            //优惠卷
            if (key.equals("coupon")) {
                List<BelongTypeCouponRequest> belongTypeCouponRequestList = new ArrayList<>();
                for (Object o : req.getJSONArray(key)) {
                    JSONObject coupon = (JSONObject) o;
                    BelongTypeCouponRequest belongTypeCouponRequest = new BelongTypeCouponRequest();
                    belongTypeCouponRequest.setBelongType(coupon.getInt("type"));
                    belongTypeCouponRequest.setCouponId(coupon.getLong("id"));
                    belongTypeCouponRequestList.add(belongTypeCouponRequest);
                }
                ReceiveCouponBelongTypeBO receiveCouponBelongTypeBO = new ReceiveCouponBelongTypeBO();
                receiveCouponBelongTypeBO.setShopId(shopId);
                receiveCouponBelongTypeBO.setCouponList(belongTypeCouponRequestList);
                Wrapper<List<CanReceiveCouponBO>> couponWrapper = couponCalculateService.checkReceiveCoupon(user, receiveCouponBelongTypeBO);
                if (couponWrapper.getCode() == ResponseCode.SUCCESS.getCode() && CollectionUtil.isNotEmpty(couponWrapper.getData())) {
                    List<Map<String, Object>> couponMapList = couponWrapper.getData().stream().map(a -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", a.getCouponId());
                        map.put("name", a.getName());
                        map.put("type", a.getType());
                        map.put("typeName", a.getTypeName());
                        map.put("releaseTimeStart", a.getReleaseTimeStart());
                        map.put("releaseTimeEnd", a.getReleaseTimeEnd());
                        map.put("denomination", a.getDenomination());
                        map.put("getWay", a.getGetWay());
                        map.put("getWayName", PlatformCouponGetWayEnum.getCodeMessage(a.getGetWay()));
                        map.put("useConditionMoney", a.getUseConditionMoney());
                        map.put("createTime", a.getCreateTime());
                        // 没看懂这个couponTypeName是干什么用
                        map.put("couponTypeName", BelongTypeEnum.PLATFORM.getCode().equals(a.getBelongType()) ? "平台优惠券" : "商家优惠券");
                        map.put("belongType", a.getBelongType());
                        map.put("belongName", BelongTypeEnum.getCodeMessage(a.getBelongType()));
                        map.put("canReceive", user == null ? CanReceiveEnum.NO_LOGIN.getCode() : a.getCanReceive().getCode());
                        map.put("effectiveType", a.getEffectiveType());
                        map.put("invalidDay", a.getInvalidDay());
                        return map;
                    }).collect(toList());
                    result.put(key, couponMapList);
                } else {
                    result.put(key, new ArrayList<>());
                }
            }

            //活动
            if (!key.equals("coupon")) {
                //获取活动商品ID
                JSONArray jsonArray = req.getJSONArray(key);
                List<Long> activityGoodsIdList = jsonArray.toList(Long.class);

                //根据活动商品ID获取平台活动的活动商品
                List<ActivityGoodsDO> activityGoodsList = goodsRepository.findAllByBelongTypeAndIdIn(
                        BelongTypeEnum.PLATFORM.getCode(),
                        activityGoodsIdList
                );
                //判断商城是否是渠道商城
                CommonIdListDTO dto = new CommonIdListDTO();
                dto.setIdList(Collections.singletonList(shopId));
                Wrapper<List<ShopVO>> ids = shopControllerFeign.byShopIds(dto);
                if (CollectionUtils.isEmpty(ids.getData())) {
                    throw new BusinessException(ResponseCode.PLATFORM_MANAGE_MALL_DOES_NOT_EXIST);
                }
                //封装查询数据
                List<CommodityNameRequest> requestList = activityGoodsList.stream().map(e -> {
                    CommodityNameRequest commodityNameRequest = new CommodityNameRequest();
                    commodityNameRequest.setCommodityId(e.getProductId());
                    commodityNameRequest.setCommodityName(e.getProductName());
                    return commodityNameRequest;
                }).collect(toList());

                //判断商品是否上架
                CommodityPublishRequest request = new CommodityPublishRequest();
                request.setShopId(shopId);
                request.setIsChannelCommodity(ShopTypeEnum.checkChannelOrChannelSelf(ids.getData().get(0).getType()));
                request.setCommodityList(requestList);
                Wrapper<List<Long>> list = commodityFeign.getCommodityListByIsPublish(request);
                List<Long> data = list.getData();
                if (data != null) {
                    activityGoodsList = activityGoodsList.stream().filter(Objects::nonNull).filter(e -> data.contains(e.getProductId())).collect(toList());
                }
                List<ActivityGoodsBO> activityGoodsBOS = activityPriceCalculateComponent.selectPlatformActivity(shopId, activityGoodsList.stream().map(ActivityGoodsDO::getProductId).collect(toList()), null);
                if (user != null) {
                    List<ActivityGoodsBO> merchantActivityDOList = activityPriceCalculateComponent.checkPlatformActivity(new MemberAndRoleIdBO(user.getMemberId(), user.getMemberRoleId()), activityGoodsBOS).getData();
                    if (!CollectionUtils.isEmpty(merchantActivityDOList)) {
                        List<Long> finalActivityGoodsIdList = merchantActivityDOList.stream().map(ActivityGoodsBO::getId).collect(toList());
                        activityGoodsList = activityGoodsList.stream().filter(p -> finalActivityGoodsIdList.contains(p.getId())).collect(toList());
                    }
                }
                //根据平台活动商品获取平台活动（活动进行中且当前时间在活动时间范围内）
                List<Long> activityIdList = activityGoodsList.stream().map(ActivityGoodsDO::getActivityId).collect(toList());
                List<PlatformActivityDO> activityList = platformActivityRepository.findAllByIdInAndOuterStatusAndStartTimeLessThanEqualAndEndTimeGreaterThanEqual(
                        activityIdList,
                        PlatformActivityOuterStatusEnum.ONGOING.getCode(),
                        System.currentTimeMillis(),
                        System.currentTimeMillis()
                );
                if (CollectionUtil.isNotEmpty(activityList)) {
                    //重新获取满足条件（活动进行中且当前时间在活动时间范围内）的活动ID，筛选出满足条件的活动商品
                    activityIdList = activityList.stream().map(PlatformActivityDO::getId).collect(toList());
                    List<Long> finalActivityIdList = activityIdList;
                    activityGoodsList = activityGoodsList.stream().filter(a -> finalActivityIdList.contains(a.getActivityId())).collect(toList());

                    //根据活动商品获取配套商品, 如果获取不到说明非此类型(赠品、换购商品、套餐)的活动
                    Map<Long, List<ActivityCardAdornResp.ActivityGoodsSubsidiaryGroupResp>> subsidiaryMap = getActivityGoodsSubsidiaryMap(activityGoodsList.stream().map(ActivityGoodsDO::getId).collect(Collectors.toList()));

                    //根据活动商品ID，获取活动商品的赠品（优惠卷）
                    Map<Long, List<Map<String, Object>>> activityGoodsGiveCoupon = getActivityGoodsGiveCouponMap(activityGoodsList.stream().map(ActivityGoodsDO::getId).collect(toList()));
                    //过滤掉不满足条件的活动商品并且组装
                    List<Map<String, Object>> activityAdornContent = activityGoodsList.stream().map(a -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", a.getId());
                        map.put("memberId", a.getMemberId());
                        map.put("roleId", a.getRoleId());
                        map.put("memberName", a.getMemberName());
                        map.put("productId", a.getProductId());
                        map.put("skuId", a.getSkuId());
                        map.put("productName", a.getProductName());
                        map.put("type", a.getType());
                        map.put("category", a.getCategory());
                        map.put("brand", a.getBrand());
                        map.put("unit", a.getUnit());
                        map.put("price", a.getPrice());
                        map.put("plummetPrice", a.getPlummetPrice());
                        map.put("deductionPrice", a.getDeductionPrice());
                        map.put("discount", a.getDiscount());
                        map.put("restrictNum", a.getRestrictNum());
                        map.put("hasSold", a.getSalesNum());
                        map.put("restrictTotalNum", a.getRestrictTotalNum());
                        map.put("productImgUrl", a.getProductImgUrl());
                        map.put("giveType", a.getGiveType());
                        BigDecimal memberDiscount = new BigDecimal("0");
                        if (user != null) {
                            MemberFeignManageUpperMemberAndRoleVO memberFeignRelationVO = new MemberFeignManageUpperMemberAndRoleVO();
                            memberFeignRelationVO.setSubMemberId(user.getMemberId());
                            memberFeignRelationVO.setSubMemberRoleId(user.getMemberRoleId());
                            memberFeignRelationVO.setParentMemberId(a.getMemberId());
                            memberFeignRelationVO.setParentMemberRoleId(a.getRoleId());
                            Wrapper<MemberFeignManageMemberCreditParameterVO> memberPriceRight = memberLevelRightCreditControllerFeign.getUpperMemberCreditParameter(memberFeignRelationVO);
                            memberDiscount = memberPriceRight.getData().getParameter();
                        }
                        map.put("activityPrice", a.getActivityPrice() != null ? memberDiscount.compareTo(new BigDecimal("0")) > 0 ? decimalFormat.format(a.getActivityPrice()) :decimalFormat.format(a.getActivityPrice().multiply(memberDiscount)): memberDiscount.compareTo(new BigDecimal("0")) > 0 ? decimalFormat.format(a.getPrice().multiply(memberDiscount)) : a.getPrice());
                        //获取skuId商品参与的所有生效的活动
                        //根据商家活动商品里的skuId再次获取出商家活动商品（可通过按sku分组后得到商家活动商品所关联的所有商家活动）
                        List<ActivityGoodsDO> activityGoodsDOList = goodsRepository.findAllByBelongTypeAndAuditStatusAndSkuId(
                                BelongTypeEnum.PLATFORM.getCode(),
                                ActivityGoodsAuditStatusEnum.AGREE.getCode(),
                                a.getSkuId()
                        );
                        //根据商家活动商品获取商家活动（活动进行中且当前时间在活动时间范围内）
                        List<MerchantActivityDO> pcActivityList = merchantActivityRepository.findAllByIdInAndInnerStatusAndStartTimeLessThanEqualAndEndTimeGreaterThanEqual(
                                activityGoodsDOList.stream().map(ActivityGoodsDO::getActivityId).collect(toList()),
                                MerchantActivityInnerStatusEnum.ONGOING.getCode(),
                                System.currentTimeMillis(),
                                System.currentTimeMillis()
                        );
                        map.put("activityList", pcActivityList);

                        //封装配套商品
                        if (CollectionUtil.isNotEmpty(subsidiaryMap)) {
                            map.put("goodsSubsidiaryGroupList", subsidiaryMap.get(a.getId()));
                        }

                        //封装赠品（优惠卷）
                        if (CollectionUtil.isNotEmpty(activityGoodsGiveCoupon)) {
                            map.put("giveCouponList", activityGoodsGiveCoupon.get(a.getId()));
                        }

                        //根据活动类型封装对应的最高优惠价与标签
                        PlatformActivityDO activity = activityList.stream().filter(b -> b.getId().equals(a.getActivityId())).findFirst().orElse(null);
                        if (activity != null) {
                            if (activity.getActivityType().equals(ActivityTypeEnum.SPECIAL_OFFER.getCode())) {
                                map.put("preferentialPrice", a.getActivityPrice());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.PLUMMET.getCode())) {
                                map.put("preferentialPrice", a.getActivityPrice());

                                map.put("label", MarketingFieldsEnum.FALL.getMessage() + a.getPlummetPrice() + MarketingFieldsEnum.YUAN.getMessage());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.DISCOUNT.getCode())) {
                                map.put("preferentialPrice", a.getActivityPrice());
                                map.put("label", decimalFormat.format(a.getDiscount().multiply(new BigDecimal("0.1"))) + MarketingFieldsEnum.FOLD_UP.getMessage());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.FULL_QUANTITY.getCode())) {
                                FullQuantityBO fullQuantityBO = (FullQuantityBO) activity.getActivityDefined();
                                if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                                    FullQuantityBO.LadderBO ladderBO = fullQuantityBO.getLadderList().stream().max(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).orElse(null);
                                    if (ladderBO != null) {
                                        map.put("preferentialPrice", a.getPrice().subtract(ladderBO.getValue().divide(ladderBO.getKey(), 2, RoundingMode.HALF_UP)));
                                        map.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.PIECE_MINUS.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage());
                                    }
                                } else if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                                    FullQuantityBO.LadderBO ladderBO = fullQuantityBO.getLadderList().stream().min(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).orElse(null);
                                    if (ladderBO != null) {
                                        map.put("preferentialPrice", a.getPrice().multiply(ladderBO.getValue().multiply(BigDecimal.valueOf(0.01))));
                                        map.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.ITEM.getMessage() + decimalFormat.format(ladderBO.getValue().multiply(new BigDecimal("0.1"))) + MarketingFieldsEnum.FOLD.getMessage());
                                    }
                                }
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.FULL_MONEY.getCode())) {
                                FullMoneyBO fullMoneyBO = (FullMoneyBO) activity.getActivityDefined();
                                if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                                    FullMoneyBO.LadderBO ladderBO = fullMoneyBO.getLadderList().stream().max(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).orElse(null);
                                    if (ladderBO != null) {
                                        if (a.getPrice().compareTo(ladderBO.getKey()) > 0) {
                                            map.put("preferentialPrice", a.getPrice().subtract(ladderBO.getValue()));
                                        } else {
                                            map.put("preferentialPrice", a.getPrice());
                                        }
                                        map.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.REDUCE.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage());

                                    }
                                } else if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                                    FullMoneyBO.LadderBO ladderBO = fullMoneyBO.getLadderList().stream().min(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).orElse(null);
                                    if (ladderBO != null) {
                                        map.put("preferentialPrice", a.getPrice().multiply(ladderBO.getValue().multiply(BigDecimal.valueOf(0.01))));
                                        map.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.YUAN.getMessage() + decimalFormat.format(ladderBO.getValue().multiply(new BigDecimal("0.1"))) + MarketingFieldsEnum.FOLD.getMessage());
                                    }
                                }
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.GIVE.getCode())) {
                                map.put("preferentialPrice", a.getPrice());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.MORE_PIECE.getCode())) {
                                MorePieceBO morePieceBO = (MorePieceBO) activity.getActivityDefined();
                                MorePieceBO.LadderBO ladderBO = morePieceBO.getLadderList().stream().min(Comparator.comparing(MorePieceBO.LadderBO::getDiscount)).orElse(null);
                                if (ladderBO != null) {
                                    map.put("preferentialPrice", a.getPrice().multiply(ladderBO.getDiscount().multiply(BigDecimal.valueOf(0.01))));
                                    map.put("label", MarketingFieldsEnum.THE_FIRST.getMessage() + ladderBO.getNum() + MarketingFieldsEnum.ITEM.getMessage() + ladderBO.getDiscount() + MarketingFieldsEnum.FOLD.getMessage());
                                }
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.COMBINATION.getCode())) {
                                CombinationBO combinationBO = (CombinationBO) activity.getActivityDefined();
                                map.put("preferentialPrice", a.getPrice());
                                map.put("label", combinationBO.getPrice() + MarketingFieldsEnum.YUAN.getMessage() + combinationBO.getNum() + MarketingFieldsEnum.ITEM.getMessage());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.GROUP_PURCHASE.getCode())) {
                                map.put("preferentialPrice", a.getActivityPrice());
                                //获取拼团人数
                                JSONObject jsonObject = baseActivityService.getActivityDefine(BelongTypeEnum.PLATFORM, activity.getActivityType(), activity.getActivityDefined());
                                map.put("label", jsonObject.get("assembleNum") + MarketingFieldsEnum.GROUP_OF_PEOPLE.getMessage());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.BARGAIN.getCode())) {
                                map.put("preferentialPrice", a.getActivityPrice());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.SEC_KILL.getCode())) {
                                map.put("preferentialPrice", a.getActivityPrice());

                                //秒杀时间段
                                SecKillBO secKillBO = (SecKillBO) activity.getActivityDefined();
                                map.put("secKillStartTime", secKillBO.getStartTime());
                                map.put("secKillEndTime", secKillBO.getEndTime());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.SWAP.getCode())) {
                                map.put("label", MarketingFieldsEnum.REDEMPTION.getMessage());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.PRE_SALE.getCode())) {
                                map.put("preferentialPrice", a.getPreSelPrice());
                                map.put("label", MarketingFieldsEnum.EARNEST_MONEY.getMessage() + a.getActivityPrice() + MarketingFieldsEnum.YUAN_ARRIVES.getMessage() + a.getDeductionPrice() + MarketingFieldsEnum.YUAN.getMessage());
                            }
                        }

                        return map;
                    }).collect(toList());
                    result.put(key, activityAdornContent);
                } else {
                    result.put(key, new ArrayList<>());
                }
            }
        });

        return Wrapper.success(result);
    }

    /**
     * 商家活动页（装修）
     **/
    @Override
    public Wrapper<Map<String, Object>> merchantActivityPageAdorn(JSONObject req, Long shopId, UserLoginCacheDTO user) {
        //处理数据BigDecimal 专用
        DecimalFormat decimalFormat = new DecimalFormat("##########.##########");
        //定义返回体
        Map<String, Object> result = new HashMap<>();
        //获取区域编码
        String pCode = "0";
        String cCode = "0";
        JSONArray area = req.getJSONArray("area");
        if (area != null) {
            List<String> areaList = area.toList(String.class);
            if (area.size() > 0) {
                pCode = areaList.get(0);//省code
                cCode = areaList.get(1);//市code
            }
        }
        //移除数据,防止循环操作时数据多余
        req.remove("area");
        //获取所有key，根据每个key对应的id数组查询对应的数据并组装回去
        Set<String> keySet = req.keySet();

        String finalPCode = pCode;
        String finalCCode = cCode;
        keySet.forEach(key -> {

            //优惠卷
            if (key.equals("coupon")) {
                List<BelongTypeCouponRequest> belongTypeCouponRequestList = new ArrayList<>();
                for (Object o : req.getJSONArray(key)) {
                    JSONObject coupon = (JSONObject) o;
                    BelongTypeCouponRequest belongTypeCouponRequest = new BelongTypeCouponRequest();
                    belongTypeCouponRequest.setBelongType(coupon.getInt("type"));
                    belongTypeCouponRequest.setCouponId(coupon.getLong("id"));
                    belongTypeCouponRequestList.add(belongTypeCouponRequest);
                }
                ReceiveCouponBelongTypeBO receiveCouponBelongTypeBO = new ReceiveCouponBelongTypeBO();
                receiveCouponBelongTypeBO.setShopId(shopId);
                receiveCouponBelongTypeBO.setCouponList(belongTypeCouponRequestList);
                Wrapper<List<CanReceiveCouponBO>> couponWrapper = couponCalculateService.checkReceiveCoupon(user, receiveCouponBelongTypeBO);
                if (couponWrapper.getCode() == ResponseCode.SUCCESS.getCode()) {
                    List<Map<String, Object>> couponMapList = couponWrapper.getData().stream().map(a -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", a.getCouponId());
                        map.put("name", a.getName());
                        map.put("type", a.getType());
                        map.put("typeName", a.getTypeName());
                        map.put("releaseTimeStart", a.getReleaseTimeStart());
                        map.put("releaseTimeEnd", a.getReleaseTimeEnd());
                        map.put("denomination", a.getDenomination());
                        map.put("getWay", a.getGetWay());
                        map.put("getWayName", MerchantCouponGetWayEnum.getCodeMessage(a.getGetWay()));
                        map.put("useConditionMoney", a.getUseConditionMoney());
                        map.put("createTime", a.getCreateTime());
                        // 没看懂这个couponTypeName是干什么用
                        map.put("couponTypeName", BelongTypeEnum.PLATFORM.getCode().equals(a.getBelongType()) ? "平台优惠券" : "商家优惠券");
                        map.put("belongType", a.getBelongType());
                        map.put("belongName", BelongTypeEnum.getCodeMessage(a.getBelongType()));
                        map.put("canReceive", user == null ? CanReceiveEnum.NO_LOGIN.getCode() : a.getCanReceive().getCode());
                        map.put("effectiveType", a.getEffectiveType());
                        map.put("invalidDay", a.getInvalidDay());
                        return map;
                    }).collect(toList());
                    result.put(key, couponMapList);
                } else {
                    result.put(key, new ArrayList<>());
                }
            }

            //活动
            if (!key.equals("coupon")) {
                //获取活动商品ID
                JSONArray jsonArray = req.getJSONArray(key);
                List<Long> activityGoodsIdList = jsonArray.toList(Long.class);

                //根据活动商品ID获取平台活动的活动商品
                List<ActivityGoodsDO> activityGoodsList = goodsRepository.findAllByBelongTypeAndIdIn(
                        BelongTypeEnum.MERCHANT.getCode(),
                        activityGoodsIdList
                );
                //判断商城是否是渠道商城
                CommonIdListDTO dto = new CommonIdListDTO();
                dto.setIdList(Collections.singletonList(shopId));
                Wrapper<List<ShopVO>> ids = shopControllerFeign.byShopIds(dto);
                if (CollectionUtils.isEmpty(ids.getData())) {
                    throw new BusinessException(ResponseCode.PLATFORM_MANAGE_MALL_DOES_NOT_EXIST);
                }
                //封装查询数据
                List<CommodityNameRequest> requestList = activityGoodsList.stream().map(e -> {
                    CommodityNameRequest commodityNameRequest = new CommodityNameRequest();
                    commodityNameRequest.setCommodityId(e.getProductId());
                    commodityNameRequest.setCommodityName(e.getProductName());
                    return commodityNameRequest;
                }).collect(toList());

                //判断商品是否上架
                CommodityPublishRequest request = new CommodityPublishRequest();
                request.setShopId(shopId);
                request.setIsChannelCommodity(ShopTypeEnum.checkChannelOrChannelSelf(ids.getData().get(0).getType()));
                request.setCommodityList(requestList);
                Wrapper<List<Long>> list = commodityFeign.getCommodityListByIsPublish(request);
                List<Long> data = list.getData();
                if (data != null) {
                    activityGoodsList = activityGoodsList.stream().filter(Objects::nonNull).filter(e -> data.contains(e.getProductId())).collect(toList());
                }
                //根据会员筛选活动
                List<ActivityGoodsBO> activityGoodsBOS = activityPriceCalculateComponent.selectMerchantActivity(shopId, activityGoodsList.stream().map(ActivityGoodsDO::getProductId).collect(toList()), null);

                BigDecimal memberDiscount = new BigDecimal("0");
                if (user != null) {
                    //商家活动页的商家都是同一个
                    if (activityGoodsList.size() > 0) {
                        MemberFeignManageUpperMemberAndRoleVO memberFeignRelationVO = new MemberFeignManageUpperMemberAndRoleVO();
                        memberFeignRelationVO.setSubMemberId(user.getMemberId());
                        memberFeignRelationVO.setSubMemberRoleId(user.getMemberRoleId());
                        memberFeignRelationVO.setParentMemberId(activityGoodsList.get(0).getMemberId());
                        memberFeignRelationVO.setParentMemberRoleId(activityGoodsList.get(0).getRoleId());
                        Wrapper<MemberFeignManageMemberCreditParameterVO> memberPriceRight = memberLevelRightCreditControllerFeign.getUpperMemberCreditParameter(memberFeignRelationVO);
                        memberDiscount = memberPriceRight.getData().getParameter();
                    }
                    List<ActivityGoodsBO> merchantActivityDOList = activityPriceCalculateComponent.checkMerchantActivity(new MemberAndRoleIdBO(user.getMemberId(), user.getMemberRoleId()), activityGoodsBOS).getData();
                    List<Long> finalActivityGoodsIdList = merchantActivityDOList.stream().map(ActivityGoodsBO::getId).collect(toList());
                    activityGoodsList = activityGoodsList.stream().filter(p -> finalActivityGoodsIdList.contains(p.getId())).collect(toList());
                }
                //根据商家活动商品获取商家活动（活动进行中且当前时间在活动时间范围内）
                List<Long> activityIdList = activityGoodsList.stream().map(ActivityGoodsDO::getActivityId).collect(toList());
                List<MerchantActivityDO> activityList = merchantActivityRepository.findAllByIdInAndInnerStatusAndStartTimeLessThanEqualAndEndTimeGreaterThanEqual(
                        activityIdList,
                        MerchantActivityInnerStatusEnum.ONGOING.getCode(),
                        System.currentTimeMillis(),
                        System.currentTimeMillis()
                );

                if (CollectionUtil.isNotEmpty(activityList)) {
                    //重新获取满足条件（活动进行中且当前时间在活动时间范围内）的活动ID，筛选出满足条件的活动商品
                    activityIdList = activityList.stream().map(MerchantActivityDO::getId).collect(toList());
                    List<Long> finalActivityIdList = activityIdList;
                    activityGoodsList = activityGoodsList.stream().filter(a -> finalActivityIdList.contains(a.getActivityId())).collect(toList());

                    //根据活动商品获取配套商品, 如果获取不到说明非此类型(赠品、换购商品、套餐)的活动
                    Map<Long, List<ActivityCardAdornResp.ActivityGoodsSubsidiaryGroupResp>> subsidiaryMap = getActivityGoodsSubsidiaryMap(activityGoodsList.stream().map(ActivityGoodsDO::getId).collect(Collectors.toList()));

                    //根据活动商品ID，获取活动商品的赠品（优惠卷）
                    Map<Long, List<Map<String, Object>>> activityGoodsGiveCoupon = getActivityGoodsGiveCouponMap(activityGoodsList.stream().map(ActivityGoodsDO::getId).collect(toList()));

                    //过滤掉不满足条件的活动商品并且组装
                    BigDecimal finalMemberDiscount = memberDiscount;
                    List<Map<String, Object>> activityAdornContent = activityGoodsList.stream().map(a -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", a.getId());
                        map.put("memberId", a.getMemberId());
                        map.put("roleId", a.getRoleId());
                        map.put("memberName", a.getMemberName());
                        map.put("productId", a.getProductId());
                        map.put("skuId", a.getSkuId());
                        map.put("productName", a.getProductName());
                        map.put("type", a.getType());
                        map.put("category", a.getCategory());
                        map.put("brand", a.getBrand());
                        map.put("unit", a.getUnit());
                        map.put("price", a.getPrice());
                        map.put("preSalePrice", a.getPreSelPrice());
                        map.put("plummetPrice", a.getPlummetPrice());
                        map.put("activityPrice", a.getActivityPrice() != null ?  finalMemberDiscount.compareTo(new BigDecimal("0")) > 0 ? decimalFormat.format(a.getActivityPrice()) :decimalFormat.format(a.getActivityPrice().multiply(finalMemberDiscount)): finalMemberDiscount.compareTo(new BigDecimal("0")) > 0 ? decimalFormat.format(a.getPrice().multiply(finalMemberDiscount)) : a.getPrice());
                        map.put("deductionPrice", a.getDeductionPrice());
                        map.put("discount", a.getDiscount());
                        map.put("restrictNum", a.getRestrictNum());
                        map.put("hasSold", a.getSalesNum());
                        map.put("restrictTotalNum", a.getRestrictTotalNum());
                        map.put("productImgUrl", a.getProductImgUrl());
                        map.put("giveType", a.getGiveType());
                        //获取skuId商品参与的所有生效的活动
                        //根据商家活动商品里的skuId再次获取出商家活动商品（可通过按sku分组后得到商家活动商品所关联的所有商家活动）
                        List<ActivityGoodsDO> activityGoodsDOList = goodsRepository.findAllByBelongTypeAndAuditStatusAndSkuId(
                                BelongTypeEnum.MERCHANT.getCode(),
                                ActivityGoodsAuditStatusEnum.AGREE.getCode(),
                                a.getSkuId()
                        );
                        //根据商家活动商品获取商家活动（活动进行中且当前时间在活动时间范围内）
                        List<MerchantActivityDO> mcActivityList = merchantActivityRepository.findAllByIdInAndInnerStatusAndStartTimeLessThanEqualAndEndTimeGreaterThanEqual(
                                activityGoodsDOList.stream().map(ActivityGoodsDO::getActivityId).collect(toList()),
                                MerchantActivityInnerStatusEnum.ONGOING.getCode(),
                                System.currentTimeMillis(),
                                System.currentTimeMillis()
                        );
                        map.put("activityList", mcActivityList);

                        //封装配套商品
                        if (CollectionUtil.isNotEmpty(subsidiaryMap)) {
                            map.put("goodsSubsidiaryGroupList", subsidiaryMap.get(a.getId()));
                        }

                        //封装赠品（优惠卷）
                        if (CollectionUtil.isNotEmpty(activityGoodsGiveCoupon)) {
                            map.put("giveCouponList", activityGoodsGiveCoupon.get(a.getId()));
                        }

                        //根据活动类型封装对应的最高优惠价与标签
                        MerchantActivityDO activity = activityList.stream().filter(b -> b.getId().equals(a.getActivityId())).findFirst().orElse(null);
                        if (activity != null) {
                            if (activity.getActivityType().equals(ActivityTypeEnum.SPECIAL_OFFER.getCode())) {
                                map.put("preferentialPrice", a.getActivityPrice());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.PLUMMET.getCode())) {
                                map.put("preferentialPrice", a.getActivityPrice());
                                map.put("label", MarketingFieldsEnum.FALL.getMessage() + a.getPlummetPrice() + MarketingFieldsEnum.YUAN.getMessage());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.DISCOUNT.getCode())) {
                                map.put("preferentialPrice", a.getActivityPrice());
                                map.put("label", decimalFormat.format(a.getDiscount().multiply(new BigDecimal("0.1"))) + MarketingFieldsEnum.FOLD_UP.getMessage());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.FULL_QUANTITY.getCode())) {
                                FullQuantityBO fullQuantityBO = (FullQuantityBO) activity.getActivityDefined();
                                if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                                    FullQuantityBO.LadderBO ladderBO = fullQuantityBO.getLadderList().stream().max(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).orElse(null);
                                    if (ladderBO != null) {
                                        map.put("preferentialPrice", a.getPrice().subtract(ladderBO.getValue().divide(ladderBO.getKey(), 2, RoundingMode.HALF_UP)));
                                        map.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.PIECE_MINUS.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage());
                                    }
                                } else if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                                    FullQuantityBO.LadderBO ladderBO = fullQuantityBO.getLadderList().stream().min(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).orElse(null);
                                    if (ladderBO != null) {
                                        map.put("preferentialPrice", a.getPrice().multiply(ladderBO.getValue().multiply(BigDecimal.valueOf(0.01))));
                                        map.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.ITEM.getMessage() + decimalFormat.format(ladderBO.getValue().multiply(BigDecimal.valueOf(0.1))) + MarketingFieldsEnum.FOLD.getMessage());
                                    }
                                }
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.FULL_MONEY.getCode())) {
                                FullMoneyBO fullMoneyBO = (FullMoneyBO) activity.getActivityDefined();
                                if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                                    FullMoneyBO.LadderBO ladderBO = fullMoneyBO.getLadderList().stream().max(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).orElse(null);
                                    if (ladderBO != null) {
                                        if (a.getPrice().compareTo(ladderBO.getKey()) > 0) {
                                            map.put("preferentialPrice", a.getPrice().subtract(ladderBO.getValue()));
                                        } else {
                                            map.put("preferentialPrice", a.getPrice());
                                        }
                                        map.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.REDUCE.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage());
                                    }
                                } else if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                                    FullMoneyBO.LadderBO ladderBO = fullMoneyBO.getLadderList().stream().min(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).orElse(null);
                                    if (ladderBO != null) {
                                        map.put("preferentialPrice", a.getPrice().multiply(ladderBO.getValue().multiply(BigDecimal.valueOf(0.01))));
                                        map.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.YUAN.getMessage() + decimalFormat.format(ladderBO.getValue().multiply(BigDecimal.valueOf(0.1))) + MarketingFieldsEnum.FOLD.getMessage());
                                    }
                                }
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.GIVE.getCode())) {
                                map.put("preferentialPrice", a.getPrice());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.MORE_PIECE.getCode())) {
                                MorePieceBO morePieceBO = (MorePieceBO) activity.getActivityDefined();
                                MorePieceBO.LadderBO ladderBO = morePieceBO.getLadderList().stream().min(Comparator.comparing(MorePieceBO.LadderBO::getDiscount)).orElse(null);
                                if (ladderBO != null) {
                                    map.put("preferentialPrice", a.getPrice().multiply(ladderBO.getDiscount().multiply(BigDecimal.valueOf(0.01))));
                                    map.put("label", MarketingFieldsEnum.THE_FIRST.getMessage() + ladderBO.getNum() + MarketingFieldsEnum.ITEM.getMessage() + ladderBO.getDiscount().multiply(BigDecimal.valueOf(0.1)) + MarketingFieldsEnum.FOLD.getMessage());
                                }
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.COMBINATION.getCode())) {
                                CombinationBO combinationBO = (CombinationBO) activity.getActivityDefined();
                                map.put("preferentialPrice", a.getPrice());
                                map.put("label", combinationBO.getPrice() + MarketingFieldsEnum.YUAN.getMessage() + combinationBO.getNum() + MarketingFieldsEnum.ITEM.getMessage());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.GROUP_PURCHASE.getCode())) {
                                map.put("preferentialPrice", a.getActivityPrice());
                                //获取拼团人数
                                JSONObject jsonObject = baseActivityService.getActivityDefine(BelongTypeEnum.MERCHANT, activity.getActivityType(), activity.getActivityDefined());
                                map.put("label", jsonObject.get("assembleNum") + MarketingFieldsEnum.GROUP_OF_PEOPLE.getMessage());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.BARGAIN.getCode())) {
                                map.put("preferentialPrice", a.getActivityPrice());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.SEC_KILL.getCode())) {
                                map.put("preferentialPrice", a.getActivityPrice());

                                //秒杀时间段
                                SecKillBO secKillBO = (SecKillBO) activity.getActivityDefined();
                                map.put("secKillStartTime", secKillBO.getStartTime());
                                map.put("secKillEndTime", secKillBO.getEndTime());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.SWAP.getCode())) {
                                map.put("label", MarketingFieldsEnum.REDEMPTION.getMessage());
                            } else if (activity.getActivityType().equals(ActivityTypeEnum.PRE_SALE.getCode())) {
                                map.put("preferentialPrice", a.getPreSelPrice());
                                map.put("label", MarketingFieldsEnum.EARNEST_MONEY.getMessage() + a.getActivityPrice() + MarketingFieldsEnum.YUAN_ARRIVES.getMessage() + a.getDeductionPrice() + MarketingFieldsEnum.YUAN.getMessage());
                            }
                        }

                        return map;
                    }).collect(toList());
                    result.put(key, activityAdornContent);
                } else {
                    result.put(key, new ArrayList<>());
                }
            }
        });

        return Wrapper.success(result);
    }

    /**
     * 活动卡片（装修）
     **/
    @Override
    public Wrapper<List<ActivityCardAdornResp>> activityCardAdorn(ActivityCardAdornReq req, Long shopId, UserLoginCacheDTO user) {
        //处理数据BigDecimal 专用
        DecimalFormat decimalFormat = new DecimalFormat("##########.##########");
        //根据活动商品ID获取平台活动的活动商品
        List<ActivityGoodsDO> goodsDOList = goodsRepository.findAllByBelongTypeAndIdIn(
                BelongTypeEnum.PLATFORM.getCode(),
                req.getIds()
        );
        if (CollectionUtil.isEmpty(goodsDOList)) {
            return Wrapper.success(new ArrayList<>());
        }
        List<ActivityGoodsBO> activityGoodsBOS = activityPriceCalculateComponent.selectPlatformActivity(shopId, goodsDOList.stream().map(ActivityGoodsDO::getProductId).collect(toList()), null);
        if (user != null) {
            List<ActivityGoodsBO> platformActivityDOList = activityPriceCalculateComponent.checkPlatformActivity(new MemberAndRoleIdBO(user.getMemberId(), user.getMemberRoleId()), activityGoodsBOS).getData();
            if (!CollectionUtils.isEmpty(platformActivityDOList)) {
                List<Long> finalActivityGoodsIdList = platformActivityDOList.stream().map(ActivityGoodsBO::getId).collect(toList());
                goodsDOList = goodsDOList.stream().filter(p -> finalActivityGoodsIdList.contains(p.getId())).collect(toList());
            }

        }

        //根据平台活动商品获取平台活动（活动进行中且当前时间在活动时间范围内）
        List<Long> activityIdList = goodsDOList.stream().map(ActivityGoodsDO::getActivityId).collect(toList());
        List<PlatformActivityDO> activityList = platformActivityRepository.findAllByIdInAndOuterStatusAndStartTimeLessThanEqualAndEndTimeGreaterThanEqual(
                activityIdList,
                PlatformActivityOuterStatusEnum.ONGOING.getCode(),
                System.currentTimeMillis(),
                System.currentTimeMillis()
        );
        if (CollectionUtil.isEmpty(activityList)) {
            return Wrapper.success(new ArrayList<>());
        }
        if (activityList.stream().map(PlatformActivityDO::getActivityType).collect(toSet()).size() > 1) {
            return Wrapper.fail("单个活动卡片不存在一个以上的活动类型");
        }

        //重新获取满足条件（活动进行中且当前时间在活动时间范围内）的活动ID，筛选出满足条件的活动商品
        activityIdList = activityList.stream().map(PlatformActivityDO::getId).collect(toList());
        List<Long> finalActivityIdList = activityIdList;
        goodsDOList = goodsDOList.stream().filter(a -> finalActivityIdList.contains(a.getActivityId())).collect(toList());

        //获取活动类型
        PlatformActivityDO activity = activityList.get(0);

        //校验是否包含配套商品
        Map<Long, List<ActivityCardAdornResp.ActivityGoodsSubsidiaryGroupResp>> subsidiaryMap = getActivityGoodsSubsidiaryMapByActivityType(activity.getActivityType(), goodsDOList.stream().map(ActivityGoodsDO::getId).collect(Collectors.toList()));

        //根据活动商品ID，获取活动商品的赠品（优惠卷）
        Map<Long, List<Map<String, Object>>> activityGoodsGiveCoupon = getActivityGoodsGiveCouponMap(goodsDOList.stream().map(ActivityGoodsDO::getId).collect(toList()));

        //组装活动商品数据且按参数ids进行排序
        List<ActivityCardAdornResp> result = goodsDOList.stream().sorted(
                Comparator.comparingInt(goods -> req.getIds().indexOf(goods.getId()))
        ).map(goods -> {
            //拷贝活动商品数据
            ActivityCardAdornResp activityCardAdornResp = new ActivityCardAdornResp();
            BeanUtils.copyProperties(goods, activityCardAdornResp);

            //封装配套商品
            if (CollectionUtil.isNotEmpty(subsidiaryMap)) {
                activityCardAdornResp.setGoodsSubsidiaryGroupList(subsidiaryMap.get(goods.getId()));
            }

            //封装赠品（优惠卷）
            if (CollectionUtil.isNotEmpty(activityGoodsGiveCoupon)) {
                activityCardAdornResp.setGiveCouponList(activityGoodsGiveCoupon.get(goods.getId()));
            }

            //根据活动类型封装对应的最高优惠价与标签
            if (activity.getActivityType().equals(ActivityTypeEnum.SPECIAL_OFFER.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getActivityPrice());
            } else if (activity.getActivityType().equals(ActivityTypeEnum.PLUMMET.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getActivityPrice());
                activityCardAdornResp.setLabel(MarketingFieldsEnum.FALL.getMessage() + goods.getPlummetPrice() + MarketingFieldsEnum.YUAN.getMessage());
            } else if (activity.getActivityType().equals(ActivityTypeEnum.DISCOUNT.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getActivityPrice());
                activityCardAdornResp.setLabel(decimalFormat.format(goods.getDiscount().multiply(new BigDecimal("0.1"))) + MarketingFieldsEnum.FOLD_UP.getMessage());
            } else if (activity.getActivityType().equals(ActivityTypeEnum.FULL_QUANTITY.getCode())) {
                FullQuantityBO fullQuantityBO = (FullQuantityBO) activity.getActivityDefined();
                if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                    FullQuantityBO.LadderBO ladderBO = fullQuantityBO.getLadderList().stream().max(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).orElse(null);
                    if (ladderBO != null) {
                        activityCardAdornResp.setPreferentialPrice(goods.getPrice().subtract(ladderBO.getValue().divide(ladderBO.getKey(), 2, RoundingMode.HALF_UP)));
                        activityCardAdornResp.setLabel(MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.PIECE_MINUS.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage());
                    }
                } else if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                    FullQuantityBO.LadderBO ladderBO = fullQuantityBO.getLadderList().stream().min(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).orElse(null);
                    if (ladderBO != null) {
                        activityCardAdornResp.setPreferentialPrice(goods.getPrice().multiply(ladderBO.getValue().multiply(BigDecimal.valueOf(0.01))));
                        activityCardAdornResp.setLabel(MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.ITEM.getMessage() + decimalFormat.format(ladderBO.getValue().multiply(BigDecimal.valueOf(0.1))) + MarketingFieldsEnum.FOLD.getMessage());
                    }
                }
            } else if (activity.getActivityType().equals(ActivityTypeEnum.FULL_MONEY.getCode())) {
                FullMoneyBO fullMoneyBO = (FullMoneyBO) activity.getActivityDefined();
                if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                    FullMoneyBO.LadderBO ladderBO = fullMoneyBO.getLadderList().stream().max(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).orElse(null);
                    if (ladderBO != null) {
                        activityCardAdornResp.setPreferentialPrice(goods.getPrice().subtract(goods.getPrice().multiply(ladderBO.getValue().divide(ladderBO.getKey(), 2, RoundingMode.HALF_UP))));
                        activityCardAdornResp.setLabel(MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.REDUCE.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage());
                    }
                } else if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                    FullMoneyBO.LadderBO ladderBO = fullMoneyBO.getLadderList().stream().min(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).orElse(null);
                    if (ladderBO != null) {
                        activityCardAdornResp.setPreferentialPrice(goods.getPrice().multiply(ladderBO.getValue().multiply(BigDecimal.valueOf(0.01))));
                        activityCardAdornResp.setLabel(MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.YUAN.getMessage() + decimalFormat.format(ladderBO.getValue().multiply(BigDecimal.valueOf(0.1))) + MarketingFieldsEnum.FOLD.getMessage());
                    }
                }
            } else if (activity.getActivityType().equals(ActivityTypeEnum.GIVE.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getPrice());
            } else if (activity.getActivityType().equals(ActivityTypeEnum.MORE_PIECE.getCode())) {
                MorePieceBO morePieceBO = (MorePieceBO) activity.getActivityDefined();
                MorePieceBO.LadderBO ladderBO = morePieceBO.getLadderList().stream().min(Comparator.comparing(MorePieceBO.LadderBO::getDiscount)).orElse(null);
                if (ladderBO != null) {
                    activityCardAdornResp.setPreferentialPrice(goods.getPrice().multiply(ladderBO.getDiscount().multiply(BigDecimal.valueOf(0.01))));
                    activityCardAdornResp.setLabel(MarketingFieldsEnum.THE_FIRST.getMessage() + ladderBO.getNum() + MarketingFieldsEnum.ITEM.getMessage() + decimalFormat.format(ladderBO.getDiscount().multiply(BigDecimal.valueOf(0.1))) + MarketingFieldsEnum.FOLD.getMessage());
                }
            } else if (activity.getActivityType().equals(ActivityTypeEnum.COMBINATION.getCode())) {
                List<PlatformActivityDO> list = activityList.stream().filter(e -> e.getId().equals(goods.getActivityId())).collect(toList());
                if (CollectionUtil.isNotEmpty(list)) {
                    PlatformActivityDO platformActivityDO = list.get(0);
                    CombinationBO combinationBO = (CombinationBO) platformActivityDO.getActivityDefined();
                    activityCardAdornResp.setPreferentialPrice(goods.getPrice());
                    activityCardAdornResp.setLabel(combinationBO.getPrice() + MarketingFieldsEnum.YUAN.getMessage() + combinationBO.getNum() + MarketingFieldsEnum.ITEM.getMessage());

                }
            } else if (activity.getActivityType().equals(ActivityTypeEnum.GROUP_PURCHASE.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getActivityPrice());
                //获取拼团人数
                JSONObject jsonObject = baseActivityService.getActivityDefine(BelongTypeEnum.MERCHANT, activity.getActivityType(), activity.getActivityDefined());
                activityCardAdornResp.setLabel(jsonObject.get("assembleNum") + MarketingFieldsEnum.GROUP_OF_PEOPLE.getMessage());
            } else if (activity.getActivityType().equals(ActivityTypeEnum.BARGAIN.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getActivityPrice());
            } else if (activity.getActivityType().equals(ActivityTypeEnum.SEC_KILL.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getActivityPrice());

                //秒杀时间段
                SecKillBO secKillBO = (SecKillBO) activity.getActivityDefined();
                activityCardAdornResp.setSecKillStartTime(secKillBO.getStartTime());
                activityCardAdornResp.setSecKillEndTime(secKillBO.getEndTime());
            } else if (activity.getActivityType().equals(ActivityTypeEnum.SWAP.getCode())) {
                activityCardAdornResp.setLabel(MarketingFieldsEnum.REDEMPTION.getMessage());
            } else if (activity.getActivityType().equals(ActivityTypeEnum.PRE_SALE.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getPreSelPrice());
                activityCardAdornResp.setLabel(MarketingFieldsEnum.EARNEST_MONEY.getMessage() + goods.getActivityPrice() + MarketingFieldsEnum.YUAN_ARRIVES.getMessage() + goods.getDeductionPrice() + MarketingFieldsEnum.YUAN.getMessage());
            }

            return activityCardAdornResp;
        }).collect(Collectors.toList());

        return Wrapper.success(result);
    }

    /**
     * 店铺活动卡片（装修）
     **/
    @Override
    public Wrapper<List<ActivityCardAdornResp>> storeActivityCardAdorn(ActivityCardAdornReq req, Long shopId, UserLoginCacheDTO user) {
        //处理数据BigDecimal 专用
        DecimalFormat decimalFormat = new DecimalFormat("##########.##########");
        //根据活动商品ID获取商家活动的活动商品
        List<ActivityGoodsDO> goodsDOList = goodsRepository.findAllByBelongTypeAndIdIn(
                BelongTypeEnum.MERCHANT.getCode(),
                req.getIds()
        );
        if (CollectionUtil.isEmpty(goodsDOList)) {
            return Wrapper.success(new ArrayList<>());
        }
        List<ActivityGoodsBO> activityGoodsBOS = activityPriceCalculateComponent.selectMerchantActivity(shopId, goodsDOList.stream().map(ActivityGoodsDO::getProductId).collect(toList()), null);
        if (user != null) {
            List<ActivityGoodsBO> merchantActivityDOList = activityPriceCalculateComponent.checkMerchantActivity(new MemberAndRoleIdBO(user.getMemberId(), user.getMemberRoleId()), activityGoodsBOS).getData();
            List<Long> finalActivityGoodsIdList = merchantActivityDOList.stream().map(ActivityGoodsBO::getId).collect(toList());
            goodsDOList = goodsDOList.stream().filter(p -> finalActivityGoodsIdList.contains(p.getId())).collect(toList());
        }
        //根据商家活动商品获取商家活动（活动进行中且当前时间在活动时间范围内）
        List<Long> activityIdList = goodsDOList.stream().map(ActivityGoodsDO::getActivityId).collect(toList());
        List<MerchantActivityDO> activityList = merchantActivityRepository.findAllByIdInAndInnerStatusAndStartTimeLessThanEqualAndEndTimeGreaterThanEqual(
                activityIdList,
                MerchantActivityInnerStatusEnum.ONGOING.getCode(),
                System.currentTimeMillis(),
                System.currentTimeMillis()
        );
        if (CollectionUtil.isEmpty(activityList)) {
            return Wrapper.success(new ArrayList<>());
        }
        if (activityList.stream().map(MerchantActivityDO::getActivityType).collect(toSet()).size() > 1) {
            return Wrapper.fail("单个活动卡片不存在一个以上的活动类型");
        }

        //重新获取满足条件（活动进行中且当前时间在活动时间范围内）的活动ID，筛选出满足条件的活动商品
        activityIdList = activityList.stream().map(MerchantActivityDO::getId).collect(toList());
        List<Long> finalActivityIdList = activityIdList;
        goodsDOList = goodsDOList.stream().filter(a -> finalActivityIdList.contains(a.getActivityId())).collect(toList());

        //获取活动类型
        MerchantActivityDO activity = activityList.get(0);
        Map<Long, MerchantActivityDO> merchantActivityDOMap = activityList.stream().collect(Collectors.toMap(MerchantActivityDO::getId, o -> o));

        //校验是否包含配套商品
        Map<Long, List<ActivityCardAdornResp.ActivityGoodsSubsidiaryGroupResp>> subsidiaryMap = getActivityGoodsSubsidiaryMapByActivityType(activity.getActivityType(), goodsDOList.stream().map(ActivityGoodsDO::getId).collect(Collectors.toList()));

        //根据活动商品ID，获取活动商品的赠品（优惠卷）
        Map<Long, List<Map<String, Object>>> activityGoodsGiveCoupon = getActivityGoodsGiveCouponMap(goodsDOList.stream().map(ActivityGoodsDO::getId).collect(toList()));

        //组装活动商品数据且按参数ids进行排序
        List<ActivityCardAdornResp> result = goodsDOList.stream().sorted(
                Comparator.comparingInt(goods -> req.getIds().indexOf(goods.getId()))
        ).map(goods -> {
            //拷贝活动商品数据
            ActivityCardAdornResp activityCardAdornResp = new ActivityCardAdornResp();
            BeanUtils.copyProperties(goods, activityCardAdornResp);

            //封装配套商品
            if (CollectionUtil.isNotEmpty(subsidiaryMap)) {
                activityCardAdornResp.setGoodsSubsidiaryGroupList(subsidiaryMap.get(goods.getId()));
            }

            //封装赠品（优惠卷）
            if (CollectionUtil.isNotEmpty(activityGoodsGiveCoupon)) {
                activityCardAdornResp.setGiveCouponList(activityGoodsGiveCoupon.get(goods.getId()));
            }
            MerchantActivityDO merchantActivityDO = merchantActivityDOMap.get(goods.getActivityId());
            //根据活动类型封装对应的最高优惠价与标签
            if (merchantActivityDO.getActivityType().equals(ActivityTypeEnum.SPECIAL_OFFER.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getActivityPrice());
            } else if (merchantActivityDO.getActivityType().equals(ActivityTypeEnum.PLUMMET.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getActivityPrice());
                activityCardAdornResp.setLabel(MarketingFieldsEnum.FALL.getMessage() + goods.getPlummetPrice() + MarketingFieldsEnum.YUAN.getMessage());
            } else if (merchantActivityDO.getActivityType().equals(ActivityTypeEnum.DISCOUNT.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getActivityPrice());
                activityCardAdornResp.setLabel(decimalFormat.format(goods.getDiscount().multiply(new BigDecimal("0.1"))) + MarketingFieldsEnum.FOLD_UP.getMessage());
            } else if (merchantActivityDO.getActivityType().equals(ActivityTypeEnum.FULL_QUANTITY.getCode())) {
                FullQuantityBO fullQuantityBO = (FullQuantityBO) merchantActivityDO.getActivityDefined();
                if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                    FullQuantityBO.LadderBO ladderBO = fullQuantityBO.getLadderList().stream().max(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).orElse(null);
                    if (ladderBO != null) {
                        activityCardAdornResp.setPreferentialPrice(goods.getPrice().subtract(ladderBO.getValue().divide(ladderBO.getKey(), 2, RoundingMode.HALF_UP)));
                        activityCardAdornResp.setLabel(MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.PIECE_MINUS.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage());
                    }
                } else if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                    FullQuantityBO.LadderBO ladderBO = fullQuantityBO.getLadderList().stream().min(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).orElse(null);
                    if (ladderBO != null) {
                        activityCardAdornResp.setPreferentialPrice(goods.getPrice().multiply(ladderBO.getValue().multiply(BigDecimal.valueOf(0.01))));
                        //这是字符串接收了，如需把String转成原类型，可用 new BigDecimal()把转化后的转回去
                        String numberConverted = decimalFormat.format(ladderBO.getValue().multiply(BigDecimal.valueOf(0.01)));
                        activityCardAdornResp.setLabel(MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.ITEM.getMessage() + numberConverted + MarketingFieldsEnum.FOLD.getMessage());
                    }
                }
            } else if (merchantActivityDO.getActivityType().equals(ActivityTypeEnum.FULL_MONEY.getCode())) {
                FullMoneyBO fullMoneyBO = (FullMoneyBO) merchantActivityDO.getActivityDefined();
                if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                    FullMoneyBO.LadderBO ladderBO = fullMoneyBO.getLadderList().stream().max(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).orElse(null);
                    if (ladderBO != null) {
                        if (goods.getPrice().compareTo(ladderBO.getKey()) > 0) {
                            activityCardAdornResp.setPreferentialPrice(goods.getPrice().subtract(ladderBO.getValue()));
                        } else {
                            activityCardAdornResp.setPreferentialPrice(goods.getPrice());
                        }
                        activityCardAdornResp.setLabel(MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.REDUCE.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage());
                    }
                } else if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                    FullMoneyBO.LadderBO ladderBO = fullMoneyBO.getLadderList().stream().min(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).orElse(null);
                    if (ladderBO != null) {
                        activityCardAdornResp.setPreferentialPrice(goods.getPrice().multiply(ladderBO.getValue().multiply(BigDecimal.valueOf(0.01))));
                        activityCardAdornResp.setLabel(MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.YUAN.getMessage() + decimalFormat.format(ladderBO.getValue().multiply(BigDecimal.valueOf(0.1))) + MarketingFieldsEnum.FOLD.getMessage());
                    }
                }
            } else if (merchantActivityDO.getActivityType().equals(ActivityTypeEnum.GIVE.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getPrice());
            } else if (merchantActivityDO.getActivityType().equals(ActivityTypeEnum.MORE_PIECE.getCode())) {
                MorePieceBO morePieceBO = (MorePieceBO) merchantActivityDO.getActivityDefined();
                MorePieceBO.LadderBO ladderBO = morePieceBO.getLadderList().stream().min(Comparator.comparing(MorePieceBO.LadderBO::getDiscount)).orElse(null);
                if (ladderBO != null) {
                    activityCardAdornResp.setPreferentialPrice(goods.getPrice().multiply(ladderBO.getDiscount().multiply(BigDecimal.valueOf(0.01))));
                    activityCardAdornResp.setLabel(MarketingFieldsEnum.THE_FIRST.getMessage() + ladderBO.getNum() + MarketingFieldsEnum.ITEM.getMessage() + decimalFormat.format(ladderBO.getDiscount().multiply(BigDecimal.valueOf(0.1))) + MarketingFieldsEnum.FOLD.getMessage());
                }
            } else if (merchantActivityDO.getActivityType().equals(ActivityTypeEnum.COMBINATION.getCode())) {
                CombinationBO combinationBO = (CombinationBO) merchantActivityDO.getActivityDefined();
                activityCardAdornResp.setPreferentialPrice(goods.getPrice());
                activityCardAdornResp.setLabel(combinationBO.getPrice() + MarketingFieldsEnum.YUAN.getMessage() + combinationBO.getNum() + MarketingFieldsEnum.ITEM.getMessage());
            } else if (merchantActivityDO.getActivityType().equals(ActivityTypeEnum.GROUP_PURCHASE.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getActivityPrice());
                //获取拼团人数
                JSONObject jsonObject = baseActivityService.getActivityDefine(BelongTypeEnum.MERCHANT, merchantActivityDO.getActivityType(), merchantActivityDO.getActivityDefined());
                activityCardAdornResp.setLabel(jsonObject.get("assembleNum") + MarketingFieldsEnum.GROUP_OF_PEOPLE.getMessage());
            } else if (merchantActivityDO.getActivityType().equals(ActivityTypeEnum.BARGAIN.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getActivityPrice());
            } else if (merchantActivityDO.getActivityType().equals(ActivityTypeEnum.SEC_KILL.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getActivityPrice());
            } else if (merchantActivityDO.getActivityType().equals(ActivityTypeEnum.SWAP.getCode())) {
                activityCardAdornResp.setLabel(MarketingFieldsEnum.REDEMPTION.getMessage());
            } else if (merchantActivityDO.getActivityType().equals(ActivityTypeEnum.PRE_SALE.getCode())) {
                activityCardAdornResp.setPreferentialPrice(goods.getPreSelPrice());
                activityCardAdornResp.setLabel(MarketingFieldsEnum.EARNEST_MONEY.getMessage() + goods.getActivityPrice() + MarketingFieldsEnum.YUAN_ARRIVES.getMessage() + goods.getDeductionPrice() + MarketingFieldsEnum.YUAN.getMessage());
            }

            return activityCardAdornResp;
        }).collect(Collectors.toList());

        return Wrapper.success(result);
    }

    /**
     * 活动卡片 - 赠送优惠卷（装修）
     **/
    @Override
    public Wrapper<List<MobileMerchantActivityGoodsCouponBO>> activityCardGiveCouponAdorn(UserLoginCacheDTO user, Long shopId, ActivityCardAdornReq req) {
        List<MobileMerchantActivityGoodsCouponBO> couponList = couponCalculateService.listMerchantActivityGoodsCoupon(user, shopId, req.getIds());
        return Wrapper.success(couponList);
    }

    /**
     * 商品区（装修展示）
     **/
    @Override
    public Wrapper<PageData<GoodsAreaAdornResp>> goodsAreaAdorn(GoodsAreaAdornReq req) {
        //调用搜索服务 -> 获取商品信息
        TemplateCommoditySearchRequest searchRequest = new TemplateCommoditySearchRequest();
        searchRequest.setCurrent(req.getCurrent());
        searchRequest.setPageSize(req.getPageSize());
        searchRequest.setCategoryId(req.getCategoryId());
        searchRequest.setCustomerCategoryId(req.getCustomerCategoryId());
        searchRequest.setMemberId(req.getMemberId());
        searchRequest.setMemberRoleId(req.getMemberRoleId());
        searchRequest.setShopId(req.getShopId());
        searchRequest.setIdInList(req.getIdInList());
        searchRequest.setOrderType(req.getType().equals(1) ? 1 : null);
        searchRequest.setPriceTypeList(Stream.of(PriceTypeEnum.Cash.getCode()).collect(Collectors.toList()));
        searchRequest.setProvinceCode(req.getProvinceCode());
        searchRequest.setCityCode(req.getCityCode());
        Wrapper<PageData<CommoditySearchResponse>> wrapper = templateFeign.searchCommodityList(searchRequest);
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        if (wrapper.getData().getTotalCount().equals(0L)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //从搜索服务获取到的商品数据
        List<CommoditySearchResponse> goodsList = wrapper.getData().getData();

        //拼装
        List<GoodsAreaAdornResp> respList = goodsList.stream().map(a -> {
            GoodsAreaAdornResp resp = new GoodsAreaAdornResp();
            BeanUtils.copyProperties(a, resp);
            resp.setPrice(BigDecimal.valueOf(a.getMin()));
            if (a.getPreferentialPrice() != null && a.getPreferentialPrice().compareTo(new BigDecimal(0)) > 0) {
                resp.setMin(Double.valueOf(a.getPreferentialPrice() + ""));
                resp.setPrice(BigDecimal.valueOf(resp.getMin()));
            }
            resp.setTagList(a.getTagList());
            return resp;
        }).collect(Collectors.toList());

        //如果包含ID参数不为空则按商品ID排下序
        if (CollectionUtil.isNotEmpty(req.getIdInList())) {
            respList = respList.stream().sorted(Comparator.comparingInt(a -> req.getIdInList().indexOf(a.getId()))).collect(toList());
        }

        return Wrapper.success(new PageData<>(wrapper.getData().getTotalCount(), respList));
    }

    /**
     * 渠道商品区(装修展示)
     *
     * @param req 请求参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<GoodsAreaAdornResp>> chancelGoodsAreaAdorn(GoodsAreaAdornReq req) {
        //调用搜索服务 -> 获取渠道商品信息
        TemplateChannelCommoditySearchRequest searchRequest = new TemplateChannelCommoditySearchRequest();
        searchRequest.setCurrent(req.getCurrent());
        searchRequest.setPageSize(req.getPageSize());
        searchRequest.setShopId(req.getShopId());
        searchRequest.setCategoryId(req.getCategoryId());
        searchRequest.setMemberId(req.getMemberId());
        searchRequest.setMemberRoleId(req.getMemberRoleId());
        searchRequest.setIdInList(req.getIdInList());
        searchRequest.setOrderType(req.getType());
        searchRequest.setProvinceCode(req.getProvinceCode());
        searchRequest.setCityCode(req.getCityCode());
        Wrapper<PageData<ChannelCommoditySearchResponse>> wrapper = templateChannelFeign.searchCommodityList(searchRequest);
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        if (wrapper.getData().getTotalCount().equals(0L)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        //从搜索服务获取到的商品数据
        List<ChannelCommoditySearchResponse> goodsList = wrapper.getData().getData();

        //拼装
        List<GoodsAreaAdornResp> respList = goodsList.stream().map(a -> {
            GoodsAreaAdornResp resp = new GoodsAreaAdornResp();
            BeanUtils.copyProperties(a, resp);
            resp.setPrice(BigDecimal.valueOf(a.getMin()));
            if (a.getPreferentialPrice() != null && a.getPreferentialPrice().compareTo(new BigDecimal(0)) > 0) {
                resp.setMin(Double.valueOf(a.getPreferentialPrice() + ""));
                resp.setPrice(BigDecimal.valueOf(resp.getMin()));
            }
            return resp;
        }).collect(Collectors.toList());

        //如果包含ID参数不为空则按商品ID排下序
        if (CollectionUtil.isNotEmpty(req.getIdInList())) {
            respList = respList.stream().sorted(Comparator.comparingInt(a -> req.getIdInList().indexOf(a.getId()))).collect(toList());
        }

        return Wrapper.success(new PageData<>(wrapper.getData().getTotalCount(), respList));
    }
    // ===============================抽取的方法start===============================

    // 基于原代码抽取了一下, 服了, 同样的返回字段, 每个方法都返回一个, 还是内部类嵌套内部类, new个对象写的鬼屎这么长

    private Map<Long, List<Map<String, Object>>> getActivityGoodsGiveCouponMap(List<Long> activityGoodsIds) {
        Map<Long, List<ActivityGoodsCouponGroupBO>> goodsCouponListMap = activityGoodsHandleComponent.getActivityGoodsCouponListMap(activityGoodsIds);
        return Optional.ofNullable(goodsCouponListMap)
                .map(listMap -> listMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream().map(BeanUtil::beanToMap).collect(toList()), (e1, e2) -> e2)))
                .orElse(new HashMap<>());
    }

    private Map<Long, List<ActivityCardAdornResp.ActivityGoodsSubsidiaryGroupResp>> getActivityGoodsSubsidiaryMapByActivityType(Integer activityType, List<Long> activityGoodsIds) {
        if (!ActivityTypeEnum.containSubsidiary(activityType)) {
            return new HashMap<>();
        }
        return getActivityGoodsSubsidiaryMap(activityGoodsIds);
    }

    private Map<Long, List<ActivityCardAdornResp.ActivityGoodsSubsidiaryGroupResp>> getActivityGoodsSubsidiaryMap(List<Long> activityGoodsIds) {
        Map<Long, List<ActivityGoodsSubsidiaryGroupBO>> subsidiaryMap = activityGoodsHandleComponent.getActivityGoodsSubsidiaryListMap(activityGoodsIds);
        return Optional.ofNullable(subsidiaryMap)
                .map(listMap -> listMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream().map(bo -> {
                    ActivityCardAdornResp.ActivityGoodsSubsidiaryGroupResp activityGoodsSubsidiaryGroupResp = new ActivityCardAdornResp.ActivityGoodsSubsidiaryGroupResp();
                    activityGoodsSubsidiaryGroupResp.setGroupNo(bo.getGroupNo());
                    activityGoodsSubsidiaryGroupResp.setLimitValue(bo.getLimitValue());
                    activityGoodsSubsidiaryGroupResp.setGroupPrice(bo.getGroupPrice());

                    List<ActivityCardAdornResp.ActivityGoodsSubsidiaryGroupResp.ActivityGoodsSubsidiaryGroupDetailsResp> detailList = bo.getList().stream().map(detail -> {
                        ActivityCardAdornResp.ActivityGoodsSubsidiaryGroupResp.ActivityGoodsSubsidiaryGroupDetailsResp activityGoodsSubsidiaryGroupDetailsResp = new ActivityCardAdornResp.ActivityGoodsSubsidiaryGroupResp.ActivityGoodsSubsidiaryGroupDetailsResp();
                        activityGoodsSubsidiaryGroupDetailsResp.setId(detail.getId());
                        activityGoodsSubsidiaryGroupDetailsResp.setProductId(detail.getProductId());
                        activityGoodsSubsidiaryGroupDetailsResp.setSkuId(detail.getSkuId());
                        activityGoodsSubsidiaryGroupDetailsResp.setProductName(detail.getProductName());
                        activityGoodsSubsidiaryGroupDetailsResp.setCategory(detail.getCategory());
                        activityGoodsSubsidiaryGroupDetailsResp.setBrand(detail.getBrand());
                        activityGoodsSubsidiaryGroupDetailsResp.setUnit(detail.getUnit());
                        activityGoodsSubsidiaryGroupDetailsResp.setPrice(detail.getPrice());
                        activityGoodsSubsidiaryGroupDetailsResp.setSwapPrice(detail.getSwapPrice());
                        activityGoodsSubsidiaryGroupDetailsResp.setNum(detail.getNum());
                        activityGoodsSubsidiaryGroupDetailsResp.setProductImgUrl(detail.getProductImgUrl());
                        return activityGoodsSubsidiaryGroupDetailsResp;
                    }).collect(toList());

                    activityGoodsSubsidiaryGroupResp.setGoodsSubsidiaryGroupDetailsList(detailList);

                    return activityGoodsSubsidiaryGroupResp;

                }).collect(toList()), (e1, e2) -> e2)))
                .orElse(new HashMap<>());
    }

    // ===============================抽取的方法end===============================
}
